package com.jsb.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bokecc.bean.UploadReq;
import com.bokecc.bean.UploadRes;
import com.jsb.common.config.Global;
import com.jsb.common.utils.FileUtil;
import com.jsb.common.utils.JsonUtil;
import com.jsb.common.utils.Md5Util;
import com.jsb.common.utils.StringUtils;
import com.jsb.model.Drama;
import com.jsb.model.DramaResource;
import com.jsb.model.DramaResourceExample;
import com.jsb.model.DramaResourceExample.Criteria;
import com.jsb.service.BokeccService;
import com.jsb.service.DramaResourceService;
import com.jsb.service.DramaService;

@Controller
public class DramaResourceController{
	private static final Logger logger = Logger.getLogger(DramaResourceController.class);
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/dramaResource/list.do";
	
	@Resource
	private DramaResourceService dramaResourceService;
	
	@Resource
	private BokeccService bokeccService;
	
	@Resource
	private DramaService dramaService;
	
	@RequestMapping("/dramaResource/list")
	public String list(
			Model model,String dramaId,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		getVedios(model, dramaId, pageNum, pageSize);
		return "/DramaResource/list";
	}
	
	@RequestMapping("/dramaResource/getVedios")
	public String getAjaxList(Model model,String dramaId,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize){
		getVedios(model, dramaId, pageNum, pageSize);
		return "/DramaResource/ajaxList";
	}

	private void getVedios(Model model, String dramaId, Integer pageNum,
			Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		DramaResourceExample dramaResourceExample = new DramaResourceExample();
		Criteria createCriteria = dramaResourceExample.createCriteria();
		if(StringUtils.isNotEmpty(dramaId)){
			createCriteria.andDramaIdEqualTo(dramaId);
		}
		int totalCount = dramaResourceService.countDramaResource(dramaResourceExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		dramaResourceExample.setPageIndex((pageNum - 1) * pageSize);
		dramaResourceExample.setPageSize(pageSize);
		List<DramaResource> dramaResources = dramaResourceService.getPageDramaResource(dramaResourceExample);
		for (DramaResource dramaResource : dramaResources) {
			String dramaId2 = dramaResource.getDramaId();
			Drama drama = dramaService.getDramaByUuid(dramaId2);
			dramaResource.setDramaId(drama.getName());
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		
		model.addAttribute("dramaResources", dramaResources);
		model.addAttribute("dramaId", dramaId);
		List<Drama> dramaList = dramaService.selectByExample(null);
		model.addAttribute("dramaList", dramaList);
	}
	
	@RequestMapping("/dramaResource/toAdd")
	public String toAdd(Model model) {
		List<Drama> dramaList = dramaService.selectByExample(null);
		model.addAttribute("dramaList", dramaList);
		return "/CCboke/add";
	}

	@RequestMapping("/dramaResource/add")
	@ResponseBody
	public String add(Model model, DramaResource dramaResource) {
		try {
			dramaResource.setCreateDate(new Date());
			dramaResource.setStatus(Global.NO);
			dramaResourceService.addDramaResource(dramaResource);
			return "TRUE";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "FALSE";
	}

	@RequestMapping("/dramaResource/del")
	public String del(Model model,
			@RequestParam(value = "vid", required = true) String vid) {
		dramaResourceService.delDramaResourceByVid(vid);
		return redirect;
	}

	@RequestMapping("/dramaResource/toEdit")
	public String toEdit(Model model,
			@RequestParam(value = "vid", required = true) String vid) {
		DramaResource dramaResource = dramaResourceService.getDramaResourceByVid(vid);
		model.addAttribute("dramaResource", dramaResource);
		List<Drama> dramaList = dramaService.selectByExample(null);
		model.addAttribute("dramaList", dramaList);
		return "/DramaResource/edit";
	}

	@RequestMapping("/dramaResource/edit")
	public String edit(Model model, @ModelAttribute("dramaResource") DramaResource dramaResource) {
		dramaResourceService.updateDramaResource(dramaResource);
		return redirect;
	}

	@RequestMapping("/dramaResource/view")
	public String view(Model model,
			@RequestParam(value = "vid", required = true) String vid) {
		DramaResource dramaResource = dramaResourceService.getDramaResourceByVid(vid);
		model.addAttribute("dramaResource", dramaResource);
		return "/DramaResource/view";
	}
	
	/**
	 * 上传视频
	 * @param model
	 * @param vedio
	 * @param uploadReq
	 * @return
	 */
	@RequestMapping(value="vedio/upload",method=RequestMethod.POST)
	@ResponseBody
	public Object vedioUpload(MultipartFile vedio, String title,String dramaId,HttpServletRequest request){
		UploadRes uploadRes = new UploadRes();
		UploadReq uploadReq = new UploadReq();
		if(null==vedio){
			uploadRes.setStatus(Global.FALSE);
			uploadRes.setMsg("未选择视频");
			return uploadRes;
		}
		if(StringUtils.isEmpty(title)){
			uploadRes.setStatus(Global.FALSE);
			uploadRes.setMsg("未添加标题");
			return uploadRes;
		}
		uploadReq.setTitle(title);
		if(StringUtils.isEmpty(dramaId)){
			uploadRes.setStatus(Global.FALSE);
			uploadRes.setMsg("未选择专辑");
			return uploadRes;
		}
		uploadReq.setDramaId(dramaId);
		String md5 = null;
		File file = null;
		try {
			file = FileUtil.multipartToFile(vedio);
			md5 = Md5Util.getFileMD5String(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		long size = vedio.getSize();
		DramaResourceExample dramaResourceExample = new DramaResourceExample();
		Criteria criteria = dramaResourceExample.createCriteria();
		criteria.andMd5EqualTo(md5);
		List<DramaResource> dramaResources = dramaResourceService.selectByExample(dramaResourceExample);
		if(null != dramaResources && dramaResources.size()>0){
			uploadRes.setStatus(Global.FALSE);
			uploadRes.setMsg("该文件已经上传过");
			return uploadRes;
		}
		uploadReq.setMd5(md5);
		uploadReq.setFilesize(size);
		uploadReq.setFilename(vedio.getOriginalFilename());
		uploadReq.setFile(file);
		UploadRes res = bokeccService.vedioUpload2(uploadReq,request);
		if(null == res){
			uploadRes.setStatus(Global.FALSE);
			uploadRes.setMsg("上传失败");
			return uploadRes;
		}
		return res;
	}
	/**
	 * 视频转码完毕后的回调通知
	 * /vedio/notify?duration=10&image=http%3A%2F%2F3-img.bokecc.com%2Fcomimage%2FA0123BC413D6FBAE%2F2016-12-28%2FBE31201DC09709F99C33DC5901307461-0.jpg&status=OK&videoid=BE31201DC09709F99C33DC5901307461&time=1482908426&hash=B574CFBFF6311D823AB55978E725AB8B
	 * @param request
	 */
	@RequestMapping("vedio/notify")
	public void ccNotify(HttpServletRequest request,HttpServletResponse response){
		Map<String,String> map = new HashMap<String, String>();
		Enumeration enu=request.getParameterNames();  
		while(enu.hasMoreElements()){  
			String paraName=(String)enu.nextElement();  
			logger.error("cc转码完毕后获取到的通知参数为:"+paraName+": "+request.getParameter(paraName));
			map.put(paraName, request.getParameter(paraName));
		}
		String status = map.get("status");
		String vedioId = map.get("videoid");
		String image = map.get("image");
//		String duration = map.get("duration");
		DramaResource dramaResource = new DramaResource();
		dramaResource.setVid(vedioId);
		if(("OK").equals(status)){
			dramaResource.setSucTime(new Date());
			dramaResource.setStatus(Global.YES);
			dramaResource.setImage(image);
		}else{
			dramaResource.setStatus("-1");
		}
		dramaResourceService.updateDramaResource(dramaResource );
		String res = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><video>OK</video>";
		try {
			PrintWriter writer = response.getWriter();
			writer.write(res);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("vedio/setFree")
	public String setFree(Model model ,String vid){
		String msg = "";
		DramaResource dramaResourceByVid = dramaResourceService.getDramaResourceByVid(vid);
		if(null != dramaResourceByVid){
			Integer sort = dramaResourceByVid.getSort();
			String enable = dramaResourceByVid.getEnable();
			if(sort==1&&enable.equals("0")){
				dramaResourceByVid.setEnable("1");
				dramaResourceService.updateDramaResource(dramaResourceByVid);
				msg = "设置成功";
			}
		}else{
			msg = "设置失败";
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("msg", msg);
		String json = JsonUtil.toJson(map);
		model.addAttribute("json", json);
		return "json";
	}
	@RequestMapping("vedio/setCharge")
	public String setCharge(Model model , String vid){
		String msg = "";
		DramaResource dramaResourceByVid = dramaResourceService.getDramaResourceByVid(vid);
		if(null != dramaResourceByVid){
			String enable = dramaResourceByVid.getEnable();
			if(enable.equals("1")){
				dramaResourceByVid.setEnable("0");
				dramaResourceService.updateDramaResource(dramaResourceByVid);
				msg = "设置成功";
			}
		}else{
			msg = "设置失败";
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("msg", msg);
		String json = JsonUtil.toJson(map);
		model.addAttribute("json", json);
		return "json";
	}
}
